package org.pr.ddddesigner.infrastructure.support;

/**
 * @author chenbin
 */
public class ComponentVersion {
    public final static long LIMIT = (long) Math.pow(2, 16) - 1;
    public final static int SEGMENT_LENGTH = 3;

    public static long toNumber(int x, int y, int z) {
        if (x < 0 || x > LIMIT || y < 0 || y > LIMIT || z < 0 || z > LIMIT) {
            throw new IllegalArgumentException(String.format("版本数字超出范围 [0, %d]: %d.%d.%d", LIMIT, x, y, z));
        }
        return ((long) x << 32) | ((long) y << 16) | z;
    }

    public static long toNumber(String version) {
        String[] split = version.split("\\.");
        if (split.length == SEGMENT_LENGTH) {
            try {
                return toNumber(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
            } catch (Exception ignore) {
            }
        }
        throw new IllegalArgumentException(String.format("版本号格式错误 (x.y.z): %s", version));
    }

    public static String toString(long version) {
        return String.format("%d.%d.%d", version >> 32, (version >> 16) & 0xFFFF, version & 0xFFFF);
    }
}
